//
//  IDFaceViewController.m
//  SecondLoan
//
//  Created by 姚永波 on 2019/8/24.
//  Copyright © 2019 姚永波. All rights reserved.
//

#import "IDFaceViewController.h"
#import "SLEditInfoViewController.h"
#import "YSHYClipViewController.h"
#import "UIImage+Stretch.h"
#import "SLApplyLoacnViewController.h"
#import "CustomCameraViewController.h"
#import "CDPAuth.h"


@interface IDFaceViewController ()<CustomCameraDelegate>

@property (strong, nonatomic) MBProgressHUD *hud;
@property (strong, nonatomic) NSData *imgFaceData;
@property (nonatomic, assign) BOOL isSuccessful;
@property (strong, nonatomic) UIImage *cardImage, *livenessImage;

@end

@implementation IDFaceViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    self.title = @"请完成刷脸认证";
    MBProgressHUD *hud = [[MBProgressHUD alloc] initWithView:self.view];
    [self.view addSubview:hud];
    self.hud = hud;
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
    [button setImage:[UIImage imageNamed:@"back"] forState:UIControlStateNormal];
    button.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
    [button setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [button setTitleColor:[UIColor redColor] forState:UIControlStateHighlighted];
    [button addTarget:self action:@selector(back) forControlEvents:UIControlEventTouchUpInside];
    button.bounds = CGRectMake(0, 0, 70, 30);
    button.contentEdgeInsets = UIEdgeInsetsMake(0, -5, 0, 0);
    self.navigationItem.leftBarButtonItem =  [[UIBarButtonItem alloc] initWithCustomView:button];
    [self.navigationController setNavigationBarHidden:NO animated:animated];
}
- (void)back{
    [self.navigationController popToRootViewControllerAnimated:YES];
}



- (IBAction)faceAction:(UIButton *)sender {
//    CustomCameraViewController *pickController = [[CustomCameraViewController alloc] init];
//    pickController.delegate = self;
//    [self presentViewController:pickController animated:YES completion:nil];
    __weak __block typeof(self) weakSelf = self;
    [CDPAuth presentLivenessControllerFrom:self cancelHandler:^{
        NSLog(@"Detect canceled");
        [weakSelf showAlertWithText:@"用户取消"];
    } deviceErrorHandler:^(STIdDeveiceError errorCode) {
        NSLog(@"Detect Error");
        switch (errorCode) {
            case STID_E_CAMERA:
                [weakSelf showAlertWithText:@"相机权限获取失败:请在设置-隐私-相机中开启后重试"];
                break;
                
            case STID_WILL_RESIGN_ACTIVE:
                [weakSelf showAlertWithText:@"活体检测已经取消"];
                break;
        }
    } resultHandler:^(NSArray<UIImage *> *images) {
        NSLog(@"Detect Success");
        weakSelf.livenessImage = images.firstObject;
        [weakSelf uploadPic];
        [self.btnFace setBackgroundImage:images.firstObject forState:UIControlStateNormal];
    } failedHanlder:^(LivefaceErrorType errorType) {
        NSLog(@"Detect Failed");
        switch (errorType) {
            case STID_E_LICENSE_INVALID: {
                [weakSelf showAlertWithText:@"未通过授权验证"];
                break;
            }
            case STID_E_LICENSE_FILE_NOT_FOUND: {
                [weakSelf showAlertWithText:@"授权文件不存在"];
                break;
            }
            case STID_E_LICENSE_BUNDLE_ID_INVALID: {
                [weakSelf showAlertWithText:@"绑定包名错误"];
                break;
            }
            case STID_E_LICENSE_EXPIRE: {
                [weakSelf showAlertWithText:@"授权文件过期"];
                break;
            }
            case STID_E_LICENSE_VERSION_MISMATCH: {
                [weakSelf showAlertWithText:@"License与SDK版本不匹"];
                break;
            }
            case STID_E_LICENSE_PLATFORM_NOT_SUPPORTED: {
                [weakSelf showAlertWithText:@"License不支持当前平台"];
                break;
            }
            case STID_E_MODEL_INVALID: {
                [weakSelf showAlertWithText:@"模型文件错误"];
                break;
            }
            case STID_E_MODEL_FILE_NOT_FOUND: {
                [weakSelf showAlertWithText:@"模型文件不存在"];
                break;
            }
            case STID_E_MODEL_EXPIRE: {
                [weakSelf showAlertWithText:@"模型文件过期"];
                break;
            }
            case STID_E_NOFACE_DETECTED: {
                [weakSelf showAlertWithText:@"动作幅度过⼤,请保持人脸在屏幕中央,重试⼀次"];
                break;
            }
            case STID_FACE_OCCLUSION: {
                [weakSelf showAlertWithText:@"请调整人脸姿态，去除面部遮挡，正对屏幕重试一次"];
                break;
            }
            case STID_E_TIMEOUT: {
                [weakSelf showAlertWithText:@"检测超时,请重试一次"];
                break;
            }
            case STID_E_INVALID_ARGUMENTS: {
                [weakSelf showAlertWithText:@"参数设置不合法"];
                break;
            }
            case STID_E_CALL_API_IN_WRONG_STATE: {
                [weakSelf showAlertWithText:@"错误的方法状态调用"];
                break;
            }
            case STID_E_API_KEY_INVALID: {
                [weakSelf showAlertWithText:@"API_KEY或API_SECRET错误"];
                break;
            }
            case STID_E_SERVER_ACCESS: {
                [weakSelf showAlertWithText:@"服务器访问错误"];
                break;
            }
            case STID_E_SERVER_TIMEOUT: {
                [weakSelf showAlertWithText:@"网络连接超时，请查看网络设置，重试一次"];
                break;
            }
            case STID_E_HACK: {
                [weakSelf showAlertWithText:@"未通过活体检测"];
                break;
            }
        }
    }];
}


- (IBAction)nextAction:(UIButton *)sender {
//    self.hud.label.text = nil;
//    self.hud.mode = MBProgressHUDModeIndeterminate;
//    [self.hud showAnimated:YES];
//    __weak __block typeof(self) weakSelf = self;
    if (!self.livenessImage) {
        [self showAlertWithText:@"请进行活体识别"];
        return;
    }
//    [CDPAuth checkName:weakSelf.name idCardNumber:weakSelf.idCard product:1 handler:^(BOOL success, NSError *error, NSDictionary * result) {
//        if (success) {
//            [weakSelf uploadPic];
//        } else {
//            [weakSelf showAlertWithText:error.userInfo[NSLocalizedDescriptionKey]];
//        }
//    }];
    if (self.imgFaceData == nil) {
        WKBToastInfo(MsgHintNoFaceData);
        return;
    }
    if (self.isSuccessful) {
        if (self.isOnlyAuth) {
            [self.navigationController popToRootViewControllerAnimated:YES];
        }else{
            if (self.isForPuhuiProduct) {
                SLEditInfoViewController *editVC = [[SLEditInfoViewController alloc] init];
                [self.navigationController pushViewController:editVC animated:YES];
            }else if (self.productId) { // 认证成功 --- 可直接申请第三方贷款
                SLApplyLoacnViewController *applyVC = [[SLApplyLoacnViewController alloc] init];
                applyVC.productId = self.productId;
                [self.navigationController pushViewController:applyVC animated:YES];
            }else{
                [self.navigationController popToRootViewControllerAnimated:YES];
            }
        }
    }else{
        WKBToastInfo(MsgHintFaceFailureData);
        return;
    }
}
//- (void)finalCompare
//{
//    UIImage *image = self.livenessImage;
//    NSData *data = UIImageJPEGRepresentation(image, 1.0);
//    __weak __block typeof(self) weakSelf = self;
//    [CDPAuth finalLivenessCheckWithName:self.name idCardNumber:self.idCard livenssImageData:data product:1 handler:^(BOOL success, NSError *error, NSDictionary *info) {
//        NSLog(@"finalLivenessCheckWithName %@ - %@", success?@"Success":@"Failed", info);
//        if (success) {
//            [weakSelf.hud hideAnimated:YES];
//        } else {
//            [weakSelf showAlertWithText:error.userInfo[NSLocalizedDescriptionKey]];
//        }
//    }];
//}
- (void)uploadPic{
    UIImage *image = self.livenessImage;
    CGFloat expectWidth  = 0.;
    CGFloat expectHeight = 0;
    if (image.size.width > image.size.height) {
        expectWidth = 800;
        CGFloat imageWidth  = image.size.width;
        expectHeight= expectWidth / imageWidth * image.size.height;
    }else{
        expectHeight = 800;
        CGFloat imageHeight  = image.size.height;
        expectWidth = expectHeight / imageHeight * image.size.width;
    }
    CGSize expectSize = CGSizeMake(expectWidth, expectHeight);
    UIImage *resizeImage = [image scaleToSize:expectSize];
    NSData *imageData = UIImageJPEGRepresentation(resizeImage, .8);
    if (image) {
        self.imgFaceData = imageData;
    }
    NSMutableDictionary * param = [NSMutableDictionary dictionary];
    [param setObject:[UserLocal token] forKey:@"token"];
    [param setObject:self.idCard forKey:@"idcard"];
    [param setObject:self.name forKey:@"name"];
    NSString *encodedUp= [self.imgFaceData base64EncodedStringWithOptions:NSDataBase64Encoding64CharacterLineLength];
    [param setObject:encodedUp forKey:@"pic"];
    MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    hud.label.text = @"识别中";
    [[PLRequestManage sharedInstance] httpRequestWithUrl:HTTPAPIWITH(url_face_compare) Type:RequestPost parameters:param completeHandle:^(id  _Nullable responseObject, NSError *error) {
        [hud hideAnimated:YES];
        if (!error) {
            [self HUDshowSuccessWithStatus:@"认证成功"];
             self.isSuccessful = YES;
            // 禁止再点击
            WeakSelf
            weakSelf.btnFace.userInteractionEnabled = NO;
            [weakSelf.btnFace setTitle:@"" forState:UIControlStateNormal];
        } else {
            [self HUDshowErrorWithStatus:error.localizedDescription];
        }
    }];
}
- (void)imageCameraController:(CustomCameraViewController *)picker didFinishPickingMediaWithImage:(UIImage *)image
{
    [self ClipViewController:nil FinishClipImage:image];
}
#pragma mark - ClipViewControllerDelegate
-(void)ClipViewController:(YSHYClipViewController *)clipViewController FinishClipImage:(UIImage *)editImage {
    UIImage *image = editImage;
    CGFloat expectWidth  = 0.;
    CGFloat expectHeight = 0;
    if (image.size.width > image.size.height) {
        expectWidth = 800;
        CGFloat imageWidth  = image.size.width;
        expectHeight= expectWidth / imageWidth * image.size.height;
    }else{
        expectHeight = 800;
        CGFloat imageHeight  = image.size.height;
        expectWidth = expectHeight / imageHeight * image.size.width;
    }
    CGSize expectSize = CGSizeMake(expectWidth, expectHeight);
    UIImage *resizeImage = [image scaleToSize:expectSize];
    NSData *imageData = UIImageJPEGRepresentation(resizeImage, .8);
    if (image) {
        self.imgFaceData = imageData;
        [self.btnFace setBackgroundImage:resizeImage forState:UIControlStateNormal];
        [self dismissViewControllerAnimated:YES completion:nil];
        [self uploadPic];
    }
}

- (void)showAlertWithText:(NSString *)text
{
    if (text.length == 0) {
        text = @"未知错误";
    }
    self.hud.mode = MBProgressHUDModeText;
    self.hud.label.text = text;
    [self.hud showAnimated:YES];
    [self.hud hideAnimated:YES afterDelay:1];
}
@end
